package com.ndp.fb.walle.controller;

import com.alibaba.fastjson.JSON;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.rdb.model.Adword;
import com.ndp.fb.rdb.model.Dictionary;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.walle.business.AdwordService;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.adword.param.AdwordParam;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Title: AdwordController.java
 * Description: 广告词管理控制器
 *
 * @author Sisi 创建时间 2014年7月22日 下午3:00:19
 */
@RequestMapping("/adwords")
@Controller
public class AdwordController {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * adwordService
     */
    @Autowired
    private AdwordService adwordService;

    /**
     * 创建广告语
     * @param param
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "createAdword")
    @ResponseBody
    public ResponseEntity<String> createAdword(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("AdwordController createAdword() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;

        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AdwordParam adwordParam = JSON.parseObject(param, AdwordParam.class);
            Long id = adwordService.createAdword(user, adwordParam);

            if (null == id) {
                errorType = ErrorType.CREATE_ADWORD_FAIL;
            } else {
                data = new HashMap<>();
                data.put("id", id);
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("AdwordController createAdword() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * deleteAdword
     *
     * @param param param
     * @return ResponseEntity<String>
     */
    @RequestMapping(value = "deleteAdword")
    @ResponseBody
    public ResponseEntity<String> deleteAdword(@RequestParam(value = "param", required = true) String param, HttpServletRequest httpServletRequest) {
        logger.info("AdwordController deleteAdword() begin.");
        ErrorType errorType = null;
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AdwordParam adwordParam = JSON.parseObject(param, AdwordParam.class);
            String userId = user.getTicket();
            long resourceId = adwordParam.getId();

            Adword adword = adwordService.findById(resourceId);
            if(adword.getUserId().equals(userId)){
                boolean flag = adwordService.deleteAdword(user.getTicket(), adwordParam.getId());
                if (!flag) {
                    errorType = ErrorType.DELETE_ADWORD_FAIL;
                }
            } else {
                errorType = ErrorType.DELETE_ADWORD_FAIL_YOUS;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        logger.info("AdwordController deleteAdword() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * getAdwordsAllList  广告发布-查询全量广告语
     *
     * @param param param
     * @return ResponseEntity<String>
     */
    @RequestMapping(value = "getAdwordsAllList", method= RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getAdwordsAllList(@RequestParam(value = "param", required = true) String param,
                                                 HttpServletRequest httpServletRequest) {
        logger.info("AdwordController getAdwordsAllList() begin.");
        ErrorType errorType = null;
        List<Adword> data = null;
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AdwordParam adwordParam = JSON.parseObject(param, AdwordParam.class);
            data = adwordService.getAdwordsAllList(adwordParam.getProductId(), adwordParam.getLanguageId(), user.getOrgId());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("AdwordController getAdwordsAllList() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * getAdwordsList  广告语管理-查询广告语支持分页
     *
     * @param param param
     * @return ResponseEntity<String>
     */
    @RequestMapping(value = "getAdwordsList", method= RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> getAdwordsList(@RequestParam(value = "param", required = true) String param,
                                                    HttpServletRequest httpServletRequest) {
        logger.info("AdwordController getAdwordsList() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AdwordParam adwordParam = JSON.parseObject(param, AdwordParam.class);
            int sizeNo = adwordParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : adwordParam.getPSize();
            int firstResult = adwordParam.getCPage() == null ? 0 : (adwordParam.getCPage() - 1) * sizeNo;
            // 查询列表

            Pager<Adword> adWordPager = adwordService.getAdwordsList(adwordParam.getProductId(), adwordParam.getLanguageId(),
                    user.getOrgId(), firstResult, sizeNo);
            // 计算分页结果
            long tSize = adWordPager.getTotalSize();
            float nrOfPages = (float) tSize / sizeNo;
            int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
            PageResult pageResult = new PageResult(tPage, adwordParam.getCPage(), adwordParam.getPSize(), tSize);

            // 封装响应结果
            data = new HashMap<>();
            data.put("adwords", adWordPager.getResultList());
            data.put("paginator", pageResult);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("AdwordController getAdwordsList() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
    /**
     * searchLanguage  查询广告语设置的语言
     *
     * @param param param
     * @return ResponseEntity<String>
     */
    @RequestMapping(value = "searchLanguage", method= RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> searchLanguage(@RequestParam(value = "param", required = true) String param,
                                                 HttpServletRequest httpServletRequest) {
        logger.info("AdwordController searchLanguageByApp() begin.");
        ErrorType errorType = null;
        List<Dictionary> data = null;
        try {
            User user = (User) httpServletRequest.getSession().getAttribute("user");
            AdwordParam adwordParam = JSON.parseObject(param, AdwordParam.class);
            data = adwordService.searchLanguage(adwordParam.getProductId(),adwordParam.getDicType(), user.getOrgId(), user.getLanguage());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("AdwordController searchLanguageByApp() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
